<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="98px">
      <el-form-item label="纪念馆名称" prop="name">
        <el-input
            v-model="queryParams.name"
            placeholder="请输入纪念馆名称"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="纪念馆人数" prop="number">
        <el-select v-model="queryParams.number" placeholder="请选择纪念馆人数" clearable size="small">
          <el-option
              v-for="dict in dict.type.memorial_hall_number"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否公开" prop="isOpen">
        <el-select v-model="queryParams.isOpen" placeholder="请选择纪念馆是否公开" clearable size="small">
          <el-option
              v-for="dict in dict.type.memorial_hall_open"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否家属管理" prop="isRelativeManage">
        <el-select v-model="queryParams.isRelativeManage" placeholder="请选择是否家属管理" clearable size="small">
          <el-option label="是" value="1"/>
          <el-option label="否" value="0"/>
        </el-select>
      </el-form-item>
      <el-form-item label="纪念馆状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择纪念馆状态" clearable size="small">
          <el-option
              v-for="dict in dict.type.memorial_hall_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['service:hall:add']"
        >新建名人馆
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="hallList" @selection-change="handleSelectionChange">
      <el-table-column label="纪念馆编号" align="center" prop="id"/>
      <el-table-column label="纪念馆名称" align="center" prop="name"/>
      <el-table-column label="纪念馆人数" align="center">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.memorial_hall_number" :value="scope.row.deceaseds.length"/>
        </template>
      </el-table-column>
      <el-table-column label="是否公开" align="center" prop="isOpen">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.memorial_hall_open" :value="scope.row.isOpen"/>
        </template>
      </el-table-column>
      <el-table-column label="是否家属管理" align="center" prop="status">
        <template slot-scope="scope">
          <span>{{scope.row.famousKey?'否':'是'}}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180"/>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-popover trigger="hover" placement="top" v-if="scope.row.status === -1">
            <p>不通过原因: {{ scope.row.verifyMessage }}</p>
            <div slot="reference" class="name-wrapper">
              <dict-tag :options="dict.type.memorial_hall_status" :value="scope.row.status"/>
            </div>
          </el-popover>
          <dict-tag v-else :options="dict.type.memorial_hall_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="300" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['service:hall:edit']"
          >详情
          </el-button>
          <el-button
              v-if="scope.row.famousKey"
              size="mini"
              type="text"
              icon="el-icon-setting"
              @click="setting(scope.row)"
              v-hasPermi="['service:hall:edit']"
          >设置
          </el-button>
          <el-button
              size="mini"
              type="text"
              icon="el-icon-document"
              @click="manage(scope.row)"
              v-hasPermi="['service:hall:edit']"
          >资料
          </el-button>
          <el-button
              v-if="scope.row.famousKey"
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['service:hall:remove']"
          >删除
          </el-button>
          <el-dropdown trigger="click" @command="verify">
            <span class="el-dropdown-link">
              <i class="el-icon-coordinate">审核</i><i class="el-icon-arrow-down"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item :command="{row:scope.row,status:1}">通过</el-dropdown-item>
              <el-dropdown-item :command="{row:scope.row,status:-1}">不通过</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加纪念馆对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <div class="el-form-item el-form-item--medium" v-if="form.id && (form.famousKey ===null|| form.famousKey ==='')">
        <label class="el-form-item__label" style="width: 100px;">纪念馆类型</label>
        <div class="el-form-item__content" style="margin-left: 100px;">
          <el-radio-group v-model="form.type">
            <el-radio
                v-for="dict in dict.type.memorial_hall_type"
                :key="dict.value"
                :label="dict.value"
            >{{dict.label}}
            </el-radio>
          </el-radio-group>
        </div>
      </div>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px" :disabled="form.id && !form.famousKey">
        <el-form-item label="纪念馆人数">
          <el-radio-group v-model="deceasedNumber" @change="numberChange">
            <el-radio
                v-for="dict in dict.type.memorial_hall_number"
                :key="dict.value"
                :label="dict.value"
            >{{dict.label}}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <div class="deceased-layout" v-for="(deceased,index) in form.deceaseds" :key="index">
          <el-form-item label="逝者照片">
            <image-upload v-model="deceased.photoUrl" :limit="1" :file-size="2"/>
          </el-form-item>
          <el-form-item label="逝者姓名" :prop="'deceaseds.' + index + '.name'" :rules="rules.name">
            <el-input show-word-limit maxlength="12" v-model="deceased.name" placeholder="请输入逝者姓名"/>
          </el-form-item>
          <el-form-item label="逝者性别">
            <el-radio-group v-model="deceased.sex">
              <el-radio :label="1">男</el-radio>
              <el-radio :label="2">女</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="出生日期类型">
            <el-radio-group @change="birthdayTypeChange(deceased,index)" v-model="deceased.birthdayType">
              <el-radio :label="1">公历</el-radio>
              <el-radio :label="0" v-if="form.id && !form.famousKey">农历</el-radio>
              <el-radio :label="2">公元前</el-radio>
              <el-radio :label="3">不详</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="出生日期" :prop="'deceaseds.' + index + '.birthday'"
                        :rules="deceased.birthdayType === 3?[]:rules.birthday">
            <el-date-picker
                :disabled="deceased.birthdayType === 3"
                v-model="deceased.birthday"
                default-value="1940-01-01"
                value-format="yyyy-MM-dd"
                type="date"
                placeholder="出生日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="逝世日期类型">
            <el-radio-group @change="deathDayTypeChange(deceased,index)" v-model="deceased.deathDayType">
              <el-radio :label="1">公历</el-radio>
              <el-radio :label="0" v-if="form.id && !form.famousKey">农历</el-radio>
              <el-radio :label="2">公元前</el-radio>
              <el-radio :label="3">不详</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="逝世日期" :prop="'deceaseds.' + index + '.deathDay'"
                        :rules="deceased.deathDayType === 3?[]:rules.deathDay">
            <el-date-picker
                :disabled="deceased.deathDayType === 3"
                v-model="deceased.deathDay"
                value-format="yyyy-MM-dd"
                type="date"
                placeholder="逝世日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="墓志铭">
            <el-input show-word-limit v-model="deceased.epitaph" maxlength="20" placeholder="请输入墓志铭"/>
          </el-form-item>
          <el-form-item label="人物简介">
            <el-input show-word-limit :autosize="{ minRows: 2, maxRows: 6 }" v-model="deceased.introduction"
                      maxlength="1500" type="textarea" placeholder="请输入人物简介"/>
          </el-form-item>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <setting ref="setting" @refresh="getList" :dict-open="dict.type.memorial_hall_open"/>
    <manage ref="manage" :dict-open="dict.type.memorial_hall_open"/>
  </div>
</template>

<script>
  import {listHall, getHall, delHall, addHall, updateHall, updateHallSetting} from "@/api/service/hall";
  import {listDeceased} from "@/api/service/deceased";
  import {listRelative} from "@/api/service/relative";
  import setting from './components/setting';
  import manage from './components/manage';

  export default {
    name: "Famous-Hall",
    dicts: ['memorial_hall_level', 'memorial_hall_type', 'memorial_hall_status', 'memorial_hall_open', 'memorial_hall_number'],
    components: {
      setting,
      manage
    },
    data() {
      return {
        baseImageUrl: process.env.VUE_APP_BASE_API,
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 纪念馆表格数据
        hallList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          name: null,
          isOpen: null,
          type: 1,
          level: null,
          status: null,
          number: null,
          isRelativeManage: null
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          name: [
            {required: true, message: "逝者姓名不能为空", trigger: "blur"}
          ],
          birthday: [
            {required: true, message: "请选择出生日期", trigger: "change"}
          ],
          deathDay: [
            {required: true, message: "请选择逝世日期", trigger: "blur"}
          ]
        },
        deceasedNumber: '1',
        oldDeceaseds: [],
      };
    },
    created() {
      this.getList();
    },
    methods: {
      /** 查询纪念馆列表 */
      getList() {
        this.loading = true;
        listHall(this.queryParams).then(response => {
          this.hallList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          type: 1,
          deceaseds: [
            {
              sex: 1,
              dateType: 1,
              birthdayType: 1,
              deathDayType: 1
            }
          ]
        };
        this.deceasedNumber = '1';
        this.oldDeceaseds = [];
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加纪念馆";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids
        getHall(id).then(response => {
          this.form = response.data;
          this.form.type = this.form.type.toString();
          this.open = true;
          this.title = row.name + "纪念馆详情";
          this.loadDeceased();
          this.loadRelative();
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != null) {
              if (this.oldDeceaseds.length > this.form.deceaseds.length) {
                this.$modal.confirm('修改后将删减' + (this.oldDeceaseds.length - this.form.deceaseds.length) + '名逝者的信息，删减后无法恢复，确定修改吗？').then(() => {
                  updateHall(this.form).then(response => {
                    this.$modal.msgSuccess("修改成功");
                    this.open = false;
                    this.getList();
                  });
                }).catch(() => {
                });
              } else {
                updateHall(this.form).then(response => {
                  this.$modal.msgSuccess("修改成功");
                  this.open = false;
                  this.getList();
                });
              }
            } else {
              addHall(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$modal.confirm('是否确认删除"' + row.name + '"纪念馆？').then(function () {
          return delHall(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {
        });
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('service/hall/export', {
          ...this.queryParams
        }, `hall_${new Date().getTime()}.xlsx`)
      },
      /* 人数监听*/
      numberChange(e) {
        let count = this.form.deceaseds.length - e;
        if (count < 0) {
          if (this.oldDeceaseds.length >= e) {
            this.form.deceaseds = this.form.deceaseds.concat(this.oldDeceaseds.slice(this.form.deceaseds.length, e));
          } else {
            this.form.deceaseds = this.form.deceaseds.concat(this.oldDeceaseds.slice(this.form.deceaseds.length));
            for (let i = 0; i < e - this.oldDeceaseds.length - (this.form.id ? 0 : 1); i++) {
              this.form.deceaseds.push({
                sex: 1,
                dateType: 1,
                birthdayType: 1,
                deathDayType: 1,
              });
            }
          }
        } else {
          this.form.deceaseds.splice(this.form.deceaseds.length - count, count);
        }
        this.deceasedNumber = e;
      },
      /*出生日期类型监听*/
      birthdayTypeChange(row, index) {
        if (row.birthdayType === 1 && row.deathDayType === 1) {
          // 如果生日忌日日期类型都是公历，则日期类型为公历
          row.dateType = 1;
        } else {
          // 否则日期类型为其他
          row.dateType = 2;
        }
        this.$delete(row, 'birthday')
      },
      /*逝世日期类型监听*/
      deathDayTypeChange(row, index) {
        if (row.birthdayType === 1 && row.deathDayType === 1) {
          // 如果生日忌日日期类型都是公历，则日期类型为公历
          row.dateType = 1;
        } else {
          // 否则日期类型为其他
          row.dateType = 2;
        }
        this.$delete(row, 'deathDay')
      },
      /* 加载逝者信息 */
      loadDeceased() {
        listDeceased({hallId: this.form.id}).then(res => {
          if (res.code === 200) {
            this.deceasedNumber = res.data.length.toString();
            this.oldDeceaseds = this.oldDeceaseds.concat(res.data);
            this.$set(this.form, 'deceaseds', res.data);
          }
        });
      },
      /* 加载亲友团 */
      loadRelative() {
        listRelative({hallId: this.form.id}).then(res => {
          if (res.code === 200) {
            this.$set(this.form, 'relatives', res.data);
          }
        });
      },
      /* 纪念馆设置 */
      setting(row) {
        this.$refs.setting.show(row)
      },
      /* 纪念馆审核 */
      verify(data) {
        if (data.status === 1) {
          this.$modal.confirm('确定"' + data.row.name + '纪念馆"审核通过吗？').then(() => {
            updateHallSetting({id: data.row.id, status: data.status}).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.getList();
            });
          }).catch(() => {
          });
        } else {
          this.$modal.prompt('请输入审核不通过的原因', '请输入审核不通过的原因').then((res) => {
            updateHallSetting({id: data.row.id, status: data.status, verifyMessage: res.value}).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.getList();
            });
          }).catch(() => {
          });
        }
      },
      /* 资料管理 */
      manage(row) {
        this.$refs.manage.show(row)
      }
    }
  };
</script>

<style lang="scss" scoped>
  .deceased-layout {
    border-top: 1px solid #dddddd;
    padding-top: 24px;
  }
</style>
